package com.power.sifa.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.account.api.IHa_user_accountFeign;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.domain.YesNo;
import com.plf.common.exception.BusinessException;
import com.plf.common.utils.DateUtil;
import com.plf.core.base.dao.Ha_userDao;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.external.window.api.IWindowFeign;
import com.power.external.window.model.pojo.vo.ApproveVo;
import com.power.external.window.model.pojo.vo.FinishVo;
import com.power.flowable.api.IAct_dsn_form_defineFeign;
import com.power.sifa.approve.dao.Apl_mainDao;
import com.power.sifa.approve.model.Apl_admreview;
import com.power.sifa.approve.model.Apl_main;
import com.power.sifa.approve.model.enumeration.St_apply;
import com.power.sifa.approve.model.enumeration.Tp_admpr;
import com.power.sifa.approve.model.enumeration.Tp_applysource;
import com.power.sifa.approve.model.pageInfo.Apl_mainPageInfo;
import com.power.sifa.approve.service.Apl_admreviewService;
import com.power.sifa.approve.service.Apl_mainService;
import com.power.sifa.statistics.model.vo.BaseCountVO;
import com.power.sifa.statistics.model.vo.BaseGraphVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 业务申请主表业务层实现
 */
@Service
@Slf4j
public class Apl_mainServiceImpl extends BaseServiceImpl implements Apl_mainService {

    @Resource
    private Apl_mainDao dao;
    @Resource
    private Ha_userDao ha_userDao;
    @Resource
    private IAct_dsn_form_defineFeign iAct_dsn_form_defineFeign;
    @Resource
    private IHa_user_accountFeign iHa_user_accountFeign;
    @Resource
    private IWindowFeign iWindowFeign;
    @Resource
    private Apl_admreviewService apl_admreviewService;


    @Override
    public Apl_main getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_main apl_main) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_main.getPrimaryKey() != null) {
            Apl_main apl_mainfDb = dao.findById(apl_main.getPrimaryKey()).orElse(null);
            if (apl_mainfDb != null) {
                BeanUtils.copyProperties(apl_main, apl_mainfDb);
                dao.save(apl_mainfDb);
                return;
            }
        }
        dao.save(apl_main);
    }

    @Override
    public void removeById(Serializable id) {
        // 只有未提交的才允许删除
        Apl_main mainObj = this.getById(id);
        if (St_apply.WRITTEN != mainObj.getStatus()) {
            throw new RuntimeException("删除失败，申请不处于未提交状态");
        }

        // 一窗信息^ 如果是一窗业务, 发送通知
        if (Tp_applysource.WINDOW == mainObj.getSource()) {
            String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 受理结果通知
            ApproveVo appVo = new ApproveVo();
            appVo.setOpinion("不予受理");
            appVo.setResult("0"); // 1 受理 0 不予受理
            appVo.setUserid(mainObj.getReguserid());
            appVo.setUsername(mainObj.getRegusername());
            appVo.setTime(now);
            ResponseDTO conRef = this.iWindowFeign.confirmAccept(mainObj.getId(), appVo);
            if (0 != conRef.getCode()) {
                log.error("removeById 向一窗推送受理结果失败 applyid -> {}", mainObj.getId());
            }
            // 办结结果通知
            FinishVo finVo = new FinishVo();
            finVo.setOpinion("退件办结");
            finVo.setResult("96"); // 0 不予许可, 1 许可通过, 109 审批出件, 96 退件办结
            finVo.setUserid(mainObj.getReguserid());
            finVo.setUsername(mainObj.getRegusername());
            finVo.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            finVo.setLicenceName("行政复议受理通知书");
            finVo.setLicenceCode(mainObj.getAcceptcode());
            ResponseDTO subRes = this.iWindowFeign.submitResult(mainObj.getId(), finVo);
            if (0 != subRes.getCode()) {
                log.error("removeById 向一窗推送业务办理结果失败 applyid -> {}", mainObj.getId());
            }
        }
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_main> findAll(Apl_mainPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Apl_main> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Apl_main> list) {
        dao.saveAll(list);
    }

    @Override
    public Apl_main getByInstid(String instid) {
        return dao.getByInstid(instid);
    }

    @Override
    public List<Apl_main> getByInstids(List<String> instids) {
        return dao.getByInstids(instids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateScatid(String instid, String scatid) {
        dao.updateScatid(instid, scatid);
    }

    @Override
    public Apl_main createMain(String userid, String processkey, Apl_main faMainObj, String matid) throws BusinessException {
        ResponseDTO res = this.iAct_dsn_form_defineFeign.getMaxDefineByKey(processkey);
        if (0 != res.getCode() || null == res.getData()) {
            log.error("createMain 通过key查询最大版本的流程表单定义失败");
            throw new BusinessException("createMain 通过key查询最大版本的流程表单定义失败");
        }

        Apl_main mainObj = new Apl_main();
        Map<String, Object> data = (Map<String, Object>) res.getData();
        mainObj.setFormid((String) data.get("id"));
        Date now = new Date();
        String applyid = now.getTime() + NanoIdUtils.randomNanoId();
        mainObj.setId(applyid);
        // 查询发起人信息
        // 1. 审批进行录入的申请, 有录入人id, 查询给对应的主表字段赋值
        List<Map> userList = this.ha_userDao.findUserDeptsByUserid(userid);
        if (CollectionUtils.isEmpty(userList)) {
            log.error("根据录入人id查询信息失败");
            throw new BusinessException("根据录入人id查询信息失败");
        }
        Map userObj = userList.get(0);
        mainObj.setReguserid(userid);
        mainObj.setRegusername((String) userObj.get("fullname"));
        mainObj.setRegsectionid((String) userObj.get("sectionid"));
        mainObj.setRegsectionname((String) userObj.get("sectionname"));
        mainObj.setApplyname(faMainObj.getApplyname());
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
        mainObj.setCreatetime(date);
        mainObj.setUpdatetime(date);
        mainObj.setStatus(St_apply.COMMIT);
        mainObj.setSubtime(faMainObj.getSubtime());
        mainObj.setSource(faMainObj.getSource());
        mainObj.setMatid(matid);
        return mainObj;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        this.dao.updateStatus(id, status);
    }

    @Override
    public void updateStatusAndFinishtime(String id, Integer status, String finishtime) {
        this.dao.updateStatusAndFinishtime(id, status, finishtime);
    }

    //受理编号：数字5位, 不足补0
    private String ACCEPT_CODE_FMT = "%s受第%05d号";

    @Override
    public String generateAcceptCode() {
        String ymd = DateUtil.d2s_simple(new Date());
        Integer no = dao.queryMaxAcceptno(ymd);
        AtomicInteger atomic = new AtomicInteger(no);
        String code = String.format(ACCEPT_CODE_FMT, ymd, atomic.incrementAndGet());
        return code;
    }

    //不予受理编号：数字3位, 不足补0
    private String STOP_CODE_FMT = "赣药监受理《%s》%03d号";

    @Override
    public String generateStopCode() {
        String ymd = DateUtil.d2s_simple(new Date());
        Integer no = dao.queryMaxStopno(ymd);
        AtomicInteger atomic = new AtomicInteger(no);
        String code = String.format(STOP_CODE_FMT, ymd, atomic.incrementAndGet());
        return code;
    }


    @Override
    public void updateStatusAndCp(String id, Integer status, Integer statuscp) {
        this.dao.updateStatusAndCp(id, status, statuscp);
    }

    @Override
    public void updateStatusByInstid(Integer status, List<String> instids) {
        this.dao.updateStatusByInstid(status, instids);
    }

    @Override
    public Apl_main getOneByAcceptcode(String acceptcode) {
        List<Apl_main> resultList = dao.getOneByAcceptcode(acceptcode, "%" + acceptcode + "%");
        return CollectionUtil.isNotEmpty(resultList) ? resultList.get(0) : null;
    }

    @Override
    public List<Apl_main> getListByAcceptcode(String acceptcode) {
        return dao.getOneByAcceptcode(acceptcode, "%" + acceptcode + "%");
    }

    @Override
    public void updateAccepttime(String id, String accepttime) {
        this.dao.updateAccepttime(id, accepttime);
    }

    @Override
    public Integer countByStatus(List<String> status) {
        return this.dao.countByStatus(status);
    }

    @Override
    public Integer countByUserAndStatus(String userid, List<String> status) {
        return this.dao.countByUserAndStatus(userid, status);
    }

    @Override
    public List<Map<String, Object>> queryUserTreeByDepartids(List<String> departList) {
        // 一个调用原接口, 多个指定
        ResponseDTO res;
        if(1 == departList.size()) {
            res = this.iHa_user_accountFeign.tree(departList.get(0));
        } else {
            res = this.iHa_user_accountFeign.tree(null);
        }
        if (res.getCode() != 0) {
            log.error("queryBusineTree 查询部门结构树失败");
            throw new RuntimeException("查询部门结构树失败");
        }
        List<Map<String, Object>> deptList = (List<Map<String, Object>>) res.getData();
        if(departList.size() > 1) {
            return deptList.stream().filter(v -> departList.contains(v.get("id"))).collect(Collectors.toList());
        }
        return deptList;
    }

    @Override
    public List<Map<String, Object>> queryBusineTree(String applyid, String departid) {
        // 1. 查询部门结构
        ResponseDTO res = this.iHa_user_accountFeign.tree(departid);
        if (res.getCode() != 0) {
            log.error("queryBusineTree 查询部门结构树失败");
            throw new RuntimeException("查询部门结构树失败");
        }

        List<Map<String, Object>> deptList = (List<Map<String, Object>>) res.getData();
        if (!CollectionUtils.isEmpty(deptList)) {
            Apl_admreview admreObj = this.apl_admreviewService.getById(applyid);
            Assert.notNull(admreObj, "行政复议申请数据为空");
            // 2. 查询状态为以提交的数据
            List<Map<String, Object>> commitList = this.dao.queryListByStatus(St_apply.COMMIT);
            // 2.1 根据录入人计算出每人当前在办的案件数
            Map<String, List<Map<String, Object>>> reguserMap = new HashMap<>(16);
            List<Map<String, Object>> tempList;
            Map<String, Object> tempMap;
            for (Map<String, Object> v : commitList) {
                if (null != reguserMap.get(v.get("reguserid"))) {
                    tempList = reguserMap.get(v.get("reguserid"));
                } else {
                    tempList = new ArrayList<>(1);
                }
                tempMap = new HashMap<>(16);
                tempMap.put("id", v.get("id"));
                tempMap.put("type", "case");
                StringBuilder str = new StringBuilder();
                str.append("【" + v.get("acceptcode") + "】");
                str.append("申请人：");
                str.append(v.get("applyname"));
                str.append("，被申请人：" + v.get("targetname"));
                tempMap.put("name", str);

                // 先按照名字比, 后续再看看要不要改成代码比
                if (admreObj.getApplyname().equals(v.get("applyname"))) {
                    tempMap.put("isApplyname", YesNo.YES);
                }
                if (admreObj.getTargetname().equals(v.get("targetname"))) {
                    tempMap.put("isTargetname", YesNo.YES);
                }

                tempList.add(tempMap);
                reguserMap.put((String) v.get("reguserid"), tempList);
            }

            // 3. 递归存入数据
            this.recursionTree(deptList, reguserMap);
        }
        return deptList;
    }

    /**
     * 根据状态查询业务申请主表
     *
     * @param status
     * @return
     */
    @Override
    public List<Apl_main> getListByStatus(List<String> status) {
//        boolean allExist = status.stream().allMatch(St_apply.ALLLIST::contains);
        return this.dao.getListByStatus(status);
    }

    @Override
    public List<BaseCountVO> caseStatus(String acceptadid) {
        return this.dao.caseStatus(acceptadid);
    }

    @Override
    public List<BaseCountVO> caseReceptionStatus(String acceptadid, String year) {
        return this.dao.caseReceptionStatus(acceptadid, year);
    }

    /**
     * 统计案件类型
     *
     * @param acceptadid
     * @return
     */
    @Override
    public BaseGraphVO countCaseType(String acceptadid, String year) {
        List<String> columnList = new ArrayList<>();
        List<Long> valueList = new ArrayList<>();
        Map<String, Long> baseGraphVOList = this.dao.countCaseType(acceptadid, year);
        Tp_admpr[] tpAdmprs = Tp_admpr.values();

        /*for (String key : baseGraphVOList.keySet()) {
            columnList.add(Tp_admpr.getDescriptionByKey(Integer.parseInt(key)));
            Long value = baseGraphVOList.get(key);
            if (value != null) {
                valueList.add(value);
            } else {
                valueList.add(0L);
            }
        }
        for (Tp_admpr admpr : tpAdmprs) {
            if (!columnList.contains(Tp_admpr.getDescriptionByKey(admpr.getKey()))) {
                columnList.add(admpr.getDescription());
                valueList.add(0L);
            }
        }*/

        for (Tp_admpr admpr : tpAdmprs) {
            columnList.add(admpr.getDescription());
            Long value = baseGraphVOList.get(admpr.getKey().toString());
            if (value != null) {
                valueList.add(value);
            } else {
                valueList.add(0L);
            }
        }
        return BaseGraphVO.builder().columnList(columnList).valueList(valueList).build();
    }

    @Override
    public List<BaseCountVO> countClosingType(String acceptadid, String year) {
        List<BaseCountVO> result = new ArrayList<>();
        result.add(new BaseCountVO("1", "直接纠错", 0L));
        result.add(new BaseCountVO("2", "维持和驳回", 0L));
        result.add(new BaseCountVO("3", "间接纠错", 0L));
        List<BaseCountVO> baseCountVOS = this.dao.countTypeLVOne(acceptadid, year);
        for (BaseCountVO baseCountVO : baseCountVOS) {
            switch (baseCountVO.getKey()) {
                case "1":
                    result.get(0).setCount(baseCountVO.getCount());
                    break;
                case "2":
                    result.get(1).setCount(baseCountVO.getCount());
                    break;
                case "3":
                    result.get(2).setCount(baseCountVO.getCount());
                    break;
                default:
                    break;
            }
        }
//        BeanUtils.copyProperties(baseCountVOS, result);
        return result;
    }

    @Override
    public Map<String, List<BaseCountVO>> countClosing(String acceptadid, String year) {
        List<BaseCountVO> result = new ArrayList<>();
//        result.add(new BaseCountVO("1", "直接纠错", 0L));
//        result.add(new BaseCountVO("2", "维持和驳回", 0L));
//        result.add(new BaseCountVO("3", "间接纠错", 0L));
        result.add(new BaseCountVO("6004805", "责令履行", 0L));
        result.add(new BaseCountVO("6004807", "撤销", 0L));
        result.add(new BaseCountVO("6004803", "确认违法", 0L));
        result.add(new BaseCountVO("6005001", "经调解、和解后申请人撤回中止结案", 0L));
        result.add(new BaseCountVO("6004802", "维持", 0L));
        result.add(new BaseCountVO("6005002", "驳回", 0L));

        List<BaseCountVO> lvTwoList = this.dao.countTypeLVTwo(acceptadid, year);
        for (BaseCountVO lvTwo : lvTwoList) {
            for (BaseCountVO resultItem : result) {
                if (lvTwo.getKey().equals(resultItem.getKey())) {
                    resultItem.setCount(resultItem.getCount() + lvTwo.getCount());
                    break;
                }
            }
            if (lvTwo.getKey().equals("6004808") || lvTwo.getKey().equals("6004809")) {
                for (BaseCountVO resultItem : result) {
                    if (resultItem.getKey().equals("6005001")) {
                        resultItem.setCount(resultItem.getCount() + lvTwo.getCount());
                        break;
                    }
                }
            }
            if (lvTwo.getKey().equals("6004800") || lvTwo.getKey().equals("6004801") || lvTwo.getKey().equals("6004814")) {
                for (BaseCountVO resultItem : result) {
                    if (resultItem.getKey().equals("6005002")) {
                        resultItem.setCount(resultItem.getCount() + lvTwo.getCount());
                        break;
                    }
                }
            }
        }

        Map<String, List<BaseCountVO>> map = new HashMap<>();
        for (BaseCountVO res : result) {
            if (res.getKey().equals("6004805") || res.getKey().equals("6004807") || res.getKey().equals("6004803")) {
                String key = "直接纠错";
                extracted(map, res, key);
            } else if (res.getKey().equals("6005001")) {
                String key = "间接纠错";
                extracted(map, res, key);
            } else if (res.getKey().equals("6004802") || res.getKey().equals("6005002")) {
                String key = "维持与驳回";
                extracted(map, res, key);
            }
        }
        return map;
    }

    private static void extracted(Map<String, List<BaseCountVO>> map, BaseCountVO lvTwo, String key) {
        if (map.containsKey(key)) {
            List<BaseCountVO> list = map.get(key);
            list.add(lvTwo);
        } else {
            List<BaseCountVO> newList = new ArrayList<>();
            newList.add(lvTwo);
            map.put(key, newList);
        }
    }

    @Override
    public List<BaseCountVO> countReceiptData(String acceptadid) {
        List<BaseCountVO> baseCountVOList = this.dao.countReceiptData(acceptadid);
        return baseCountVOList;
    }

    /**
     * 递归查询顶级菜单
     *
     * @param treeData
     */
    private void recursionTree(List<Map<String, Object>> treeData, Map<String, List<Map<String, Object>>> reguserMap) {
        // 如果不是顶级节点继续递归
        for (Map<String, Object> v : treeData) {
            if ("user".equals(v.get("type"))) {
                // 存入案件记录
                if (null != reguserMap.get(v.get("id"))) {
                    List<Map<String, Object>> childlist = reguserMap.get(v.get("id"));
                    v.put("total", childlist.size());
                    for (Map<String, Object> s : childlist) {
                        s.put("pid", v.get("id"));
                        // 父节点也放相同申请人和被申请人信息
                        if (null != s.get("isApplyname") && YesNo.YES == (int) s.get("isApplyname")) {
                            v.put("isApplyname", YesNo.YES);
                        }
                        if (null != s.get("isTargetname") && YesNo.YES == (int) s.get("isTargetname")) {
                            v.put("isTargetname", YesNo.YES);
                        }
                    }
                    v.put("children", childlist);
                } else {
                    v.put("total", 0);
                }
            } else {
                List<Map<String, Object>> childlist = (List<Map<String, Object>>) v.get("children");
                if (!CollectionUtils.isEmpty(childlist)) {
                    this.recursionTree(childlist, reguserMap);
                }
            }
        }
    }
}
